package bma.common.langutil.core;

import java.util.concurrent.atomic.AtomicInteger;

public class RoundRobinInteger {

	private AtomicInteger counter;
	private int round;

	public RoundRobinInteger() {
		this(0, 100);
	}

	public RoundRobinInteger(int round) {
		this(0, round);
	}

	public RoundRobinInteger(int init, int round) {
		super();
		this.counter = new AtomicInteger(init);
		this.round = round;
	}

	public AtomicInteger getCounter() {
		return counter;
	}

	public void setCounter(AtomicInteger counter) {
		this.counter = counter;
	}

	public int getRound() {
		return round;
	}

	public void setRound(int round) {
		this.round = round;
	}

	public int next() {
		return next(this.round);
	}

	public int next(int r) {
		int v = counter.incrementAndGet();
		if (v < 0) {
			if (counter.compareAndSet(v, 0)) {
				v = 0;
			} else {
				v = counter.incrementAndGet();
			}
		}		
		return v % r;
	}

	@Override
	public String toString() {
		return this.counter + "/" + this.round;
	}
}
